package test.util.annotation.processor;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import test.util.Constants;
import test.util.annotation.Column;
import test.util.annotation.Id;

public class ColumnAnnotationProcessor {
    /**
     * Get a all mapped columns name of a entity class.
     * 
     * @author YongXia.
     * 
     * @since jdk1.6
     * @version 1.0
     * 
     * @param clazz
     * @return all mapped column.
     */
    public final static String[] getColumns(final Class<? extends Serializable> clazz) {
        List<String> columns = new ArrayList<String>();
        EntityAnnotationProcessor.validate(clazz);
        for (Method method : clazz.getDeclaredMethods()) {
            Column column = method.getAnnotation(Column.class);
            Id id = method.getAnnotation(Id.class);
            if ((null != column || null != id) && method.getReturnType() != void.class) {
                String columnName = null;
                if (id != null && StringUtils.isNotBlank(id.column()))
                    columnName = id.column();
                else if (column != null && StringUtils.isNotBlank(column.column()))
                    columnName = column.column();
                else {
                    if (method.getName().startsWith(Constants.METHOD_NAME_PREFIX_GET))
                        columnName = method.getName().substring(Constants.THREE);
                    else if (method.getName().startsWith(Constants.METHOD_NAME_PREFIX_IS))
                        columnName = method.getName().substring(Constants.TWO);
                }

                columns.add(columnName.toUpperCase());
            }
        }

        return columns.toArray(new String[0]);
    }

    private ColumnAnnotationProcessor() {
    }
}
